package com.jy.appmarket.fragment;

import java.util.Map;

import com.jy.app.market.apk.type.UidType;
import com.jy.app.market.idata.data.Login;
import com.jy.app.market.idata.data.OtherLogin;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.activity.ForgetPasswdActivity;
import com.jy.appmarket.dialog.WaitDialog;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.LoginNetEngine;
import com.jy.appmarket.network.engine.OtherLoginNetEngine;
import com.jy.appmarket.network.resultdata.LoginResult;
import com.jy.appmarket.network.resultdata.OtherLoginResult;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.utils.CryptoUtil;
import com.jy.appmarket.utils.LoginUtil;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

public class FragmentLogin extends Fragment implements OnClickListener, NetTaskListener {

	private UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");

	private EditText mPhoneNumEdit;
	private EditText mPwdEdit;
	private WaitDialog mWaitDialog;

	private String mPhoneNum;
	private String mPasswd;

	private NetTask mNetTask;
	private NetTask mNetTask2;

	private UMQQSsoHandler mQQSsoHandler;
	private UMWXHandler mWXHandler;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_login_layout, container, false);

		initViews(view);
		addLoginPlatform();
		return view;
	}

	private void initViews(View v) {
		mPhoneNumEdit = v.findViewById(R.id.user_name_edit);
		mPwdEdit = v.findViewById(R.id.pwd_edit);
		v.findViewById(R.id.login_btn).setOnClickListener(this);
		v.findViewById(R.id.forget_pwd_btn).setOnClickListener(this);
		v.findViewById(R.id.sina_login).setOnClickListener(this);
		v.findViewById(R.id.qq_login).setOnClickListener(this);
		v.findViewById(R.id.wechat_login).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_btn:
			login();
			break;
		case R.id.forget_pwd_btn:
			startActivity(new Intent(getActivity(), ForgetPasswdActivity.class));
			break;
		case R.id.sina_login:
			otherLogin(SHARE_MEDIA.SINA);
			break;
		case R.id.qq_login:
			try {
				// 这里会抛出TransactionTooLargeException
				if (mQQSsoHandler.isClientInstalled()) {
					otherLogin(SHARE_MEDIA.QQ);
				} else {
					Toast.makeText(getActivity(), "没有安装QQ", Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
			}
			break;
		case R.id.wechat_login:
			try {
				// 这里会抛出TransactionTooLargeException
				if (mWXHandler.isClientInstalled()) {
					otherLogin(SHARE_MEDIA.WEIXIN);
				} else {
					Toast.makeText(getActivity(), "没有安装微信", Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
			}
			break;
		default:
			break;
		}
	}

	private void login() {
		mPhoneNum = mPhoneNumEdit.getText().toString().trim();
		mPasswd = mPwdEdit.getText().toString();

		if (TextUtils.isEmpty(mPhoneNum)) {
			Toast.makeText(getActivity(), R.string.please_input_username, Toast.LENGTH_SHORT).show();
			return;
		}
		if (TextUtils.isEmpty(mPasswd)) {
			Toast.makeText(getActivity(), R.string.please_input_password, Toast.LENGTH_SHORT).show();
			return;
		}
		if (mPhoneNum.length() != 11) {
			Toast.makeText(getActivity(), R.string.username_format_error, Toast.LENGTH_SHORT).show();
			return;
		}

		showWaitDialog();
		LoginNetEngine engine = new LoginNetEngine(mPhoneNum, CryptoUtil.md5(mPasswd));
		mNetTask = new NetTask(getActivity(), engine, 0);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}

	private void otherLogin(final SHARE_MEDIA platform) {
		mController.doOauthVerify(getActivity(), platform, new UMAuthListener() {

			@Override
			public void onStart(SHARE_MEDIA platform) {
				Toast.makeText(getActivity(), "授权开始", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onError(SocializeException e, SHARE_MEDIA platform) {
				Toast.makeText(getActivity(), "授权错误", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}

			@Override
			public void onComplete(Bundle value, SHARE_MEDIA platform) {
				if (value == null || TextUtils.isEmpty(value.getString("uid"))) {
					Toast.makeText(getActivity(), "授权失败", Toast.LENGTH_SHORT).show();
				} else {
					showWaitDialog();
					Toast.makeText(getActivity(), "授权成功", Toast.LENGTH_SHORT).show();
					getUserInfo(platform, value.getString("uid"));
				}
			}

			@Override
			public void onCancel(SHARE_MEDIA platform) {
				Toast.makeText(getActivity(), "授权取消", Toast.LENGTH_SHORT).show();
			}
		});
	}

	/**
	 * 获取授权平台的用户信息</br>
	 */
	private void getUserInfo(final SHARE_MEDIA platform, final String uid) {
		mController.getPlatformInfo(getActivity(), platform, new UMDataListener() {

			@Override
			public void onStart() {
				// Toast.makeText(getActivity(), "获取用户信息...",
				// Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onComplete(int status, Map<String, Object> info) {
				if (status == 200 && info != null) {
					OtherLogin otherLogin = toOtherLogin(info, platform.name(), uid);
					OtherLoginNetEngine engine = new OtherLoginNetEngine(otherLogin);
					mNetTask2 = new NetTask(getActivity(), engine, 1);
					mNetTask2.setListener(FragmentLogin.this);
					new Thread(mNetTask2).start();
				} else {
					dismissWaitDialog();
					Toast.makeText(getActivity(), "获取用户信息失败" + status, Toast.LENGTH_SHORT).show();
				}

			}
		});
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		dismissWaitDialog();
		if (tag == 0) {
			LoginResult resultData = (LoginResult) engine.getResultData();
			if (!resultData.isOK()) {
				String message = resultData.getMessage();
				if (!TextUtils.isEmpty(message)) {
					Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(getActivity(), R.string.login_error, Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(getActivity(), R.string.login_success, Toast.LENGTH_SHORT).show();
				Login login = resultData.getLogin();
				AppMarketApplication.setLogin(login);
				LoginUtil.saveLogin(getActivity(), login);
				getActivity().setResult(Activity.RESULT_OK);
				getActivity().finish();
			}
		} else if (tag == 1) {
			OtherLoginResult resultData = (OtherLoginResult) engine.getResultData();
			if (!resultData.isOK()) {
				String message = resultData.getMessage();
				if (!TextUtils.isEmpty(message)) {
					Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(getActivity(), R.string.login_error, Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(getActivity(), R.string.login_success, Toast.LENGTH_SHORT).show();
				Login login = toLogin(resultData.getOtherLogin());
				AppMarketApplication.setLogin(login);
				LoginUtil.saveLogin(getActivity(), login);
				getActivity().setResult(Activity.RESULT_OK);
				getActivity().finish();
			}
		}

	}

	@Override
	public void onTaskRunError(int tag) {
		dismissWaitDialog();
		Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onTaskRunCanceled(int tag) {
		dismissWaitDialog();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onDestroy() {
		if (mNetTask != null) {
			mNetTask.setListener(null);
			mNetTask.cancel();
			mNetTask = null;
		}
		if (mNetTask2 != null) {
			mNetTask2.setListener(null);
			mNetTask2.cancel();
			mNetTask2 = null;
		}
		dismissWaitDialog();
		super.onDestroy();
	}

	private void addLoginPlatform() {
		// 添加QQ平台
		mQQSsoHandler = new UMQQSsoHandler(getActivity(), "1104848831", "i4vpuXnIbjmNUEcL");
		mQQSsoHandler.addToSocialSDK();

		// 添加微信平台
		mWXHandler = new UMWXHandler(getActivity(), "wx365c6227b8b569b0", "d4624c36b6795d1d99dcf0547af5443d");
		mWXHandler.addToSocialSDK();

	}

	private OtherLogin toOtherLogin(Map<String, Object> info, String platformTyep, String uid) {
		OtherLogin otherLogin = new OtherLogin();
		if (SHARE_MEDIA.QQ.name().equals(platformTyep)) {
			otherLogin.setIconUrl(info.get("profile_image_url").toString());
			otherLogin.setNickName(info.get("screen_name").toString());
			String sex = info.get("gender").toString();
			if ("男".equals(sex)) {
				otherLogin.setSex("1");
			} else if ("女".equals(sex)) {
				otherLogin.setSex("2");
			}
			otherLogin.setType(UidType.QQ.toString());
		} else if (SHARE_MEDIA.WEIXIN.name().equals(platformTyep)) {
			otherLogin.setIconUrl(info.get("headimgurl").toString());
			otherLogin.setNickName(info.get("nickname").toString());
			otherLogin.setSex(info.get("sex").toString());
			otherLogin.setType(UidType.WEI_XIN.toString());
		} else if (SHARE_MEDIA.SINA.name().equals(platformTyep)) {
			otherLogin.setIconUrl(info.get("profile_image_url").toString());
			otherLogin.setNickName(info.get("screen_name").toString());
			otherLogin.setSex(info.get("gender").toString());
			otherLogin.setType(UidType.SINA_WB.toString());
		}
		otherLogin.setUid(uid);
		return otherLogin;
	}

	private Login toLogin(OtherLogin info) {
		Login login = new Login();
		login.setUserId(info.getUserId());
		login.setPhoneNum(info.getPhoneNum());
		login.setNickName(info.getNickName());
		login.setIconUrl(info.getIconUrl());
		login.setSex(info.getSex());
		login.setBirthday(info.getBirthday());
		return login;
	}

	private void showWaitDialog() {
		if (mWaitDialog == null) {
			mWaitDialog = new WaitDialog(getActivity());
			mWaitDialog.setCanceledOnTouchOutside(false);
			mWaitDialog.setCancelable(false);
		}
		if (mWaitDialog.isShowing()) {
			return;
		}
		mWaitDialog.showTitle("请稍候...").show();
	}

	private void dismissWaitDialog() {
		if (mWaitDialog != null) {
			mWaitDialog.dismiss();
		}
	}
}
